﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Security.Principal;
using Subtle.Domain.Services.Interfaces;
using Subtle.Domain.Models;

namespace Subtle.Controllers
{
	/// <summary>
	/// Base Controller
	/// </summary>
	public class BaseController : Controller
	{
		/// <summary>
		/// Save Authentication
		/// </summary>
		/// <param name="username"></param>
		protected void SaveAuthentication(string username)
		{
			//FormsAuthentication
			//Can you believe we missed it?
			var ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddYears(1), true, String.Empty, FormsAuthentication.FormsCookiePath);
			string cookieContents = FormsAuthentication.Encrypt(ticket);
			var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
			{
				Expires = ticket.Expiration,
				Path = FormsAuthentication.FormsCookiePath
			};
			HttpContext.Response.Cookies.Add(cookie);
		}

		/// <summary>
		/// Get Username from the authentication ticket
		/// </summary>
		/// <returns></returns>
		protected string GetUsername()
		{
			HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
			if (authCookie != null)
			{
				FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
				FormsIdentity id = new FormsIdentity(authTicket);
				GenericPrincipal principal = new GenericPrincipal(id, null);
				return principal.Identity.Name;
			}
			return String.Empty;
		}

		/// <summary>
		/// Set Blog
		/// </summary>
		/// <param name="blog"></param>
		public void SetBlog(Blog blog)
		{
		}
	}
}
